$(function () {
    const form = layui.form
    const layer = layui.layer

    layui.use('laydate', function () {
        let laydate = layui.laydate;

        //执行一个laydate实例
        laydate.render({
            elem: '#startDate' //指定元素
        });

        //执行一个laydate实例
        laydate.render({
            elem: '#endDate' //指定元素
        });
    });


    const key = {
        start_time: '',
        end_time: "",
        title: '',
        cateid: '',
        page: 1,
        limit: 10,
    }

    const filter = {
		isID: true,
		isTitle: true,
		iscatename: true,
		isPic: true,
		isCreate_date: true,
		isIshot: true,
		isIstop: true,
		isStatus: true,
	}

    // 封装
    function getList() {
        axios({
            method: "GET",
            url: "/ydd_article/list",
            params: key,
        }).then(({ status, data: { errno, errmsg, data: { data, count } } }) => {
            if (errno) return layer.msg(errmsg, { icon: 5, time: 1000 })
            $('#num').html(count)
            renderPage(count)
            $('tbody').html(data.map(({ catename, id, ishot, istop, create_date, title, status, pic }) => {
                console.log(ishot);
                // console.log(item);
                if (ishot === 0) {
                    ishot = '<span class="iconfont icon-anniu_kaiqi" style="font-size: 50px;color:#409eff"> </span>'
                } else {
                    ishot = '<span class="iconfont icon-anniu_guanbi" style="font-size: 50px; color:#dcdfe6"> </span>'
                }
        
                if (istop === 0) {
                    istop = '<span class="iconfont icon-anniu_kaiqi" style="font-size: 50px;color:#409eff"> </span>'
                } else {
                    istop = '<span class="iconfont icon-anniu_guanbi" style="font-size: 50px; color:#dcdfe6"> </span>'
                }
                return `<tr>
                ${filter.isID ? `<td>${id}</td>` : ''}
                ${filter.isTitle ? `<td>${title}</td>` : ''}
                ${filter.iscatename ? ` <td>${catename ? catename : ''}</td>` : ''}
                ${filter.isPic ? ` <td>${pic !== 'null' ? `<img src="http://124.223.14.236:8060/${pic}" alt="">` : ''}</td>` : ''}
                ${filter.isCreate_date ? ` <td>${new Date(create_date).toLocaleDateString().replace(/\//g, '-')}</td>` : ''}
                ${filter.isIshot ? ` <td>${ishot}</td>` : ''} 
               ${filter.isIstop ? ` <td> ${istop}</td > ` : ''}} 
            ${filter.isStatus ? ` <td>
              <button class="status">${status ? status === 1 ? '草稿箱' : '待审核' : '已发布'}</button>
            </td>` : ''}
            <td>
              <ul class="right handler">
                <li class="change" data-id=${id}>
                  <i class="layui-icon layui-icon-edit"></i>
                </li>
                <li class="del" data-id=${id}>
                  <i class="layui-icon layui-icon-delete"></i>
                </li>
              </ul>
            </td>
              </tr>`
            }).join(''))
        })
    }
    getList()

    $('tbody').on('click', '.change', function () {
		const id = $(this).data('id')
		localStorage.setItem('articleId', id)
		location.href = '/youdianda_static/article-change.html'
	})
    
    // 表单
    $('.head').on('submit', function (e) {
        // 阻止默认行为
        e.preventDefault()

        key.title = $('[name="title"]').val()
        key.cateid = $('[name="cateid"]').val()
        // key.start_time = $('[name="startDate"]').val()
        // key.end_time = $('[name="endDate"]').val()

        key.pagenum = 1

        getList()
    })



    // 点击收缩
    $('#close').on('click', function () {
		$('.head').toggle()
		$('#close').hide()
		$('#open').show()
	})

	$('#open').on('click', function () {
		$('.head').show()
		$('#open').hide()
		$('#close').show()
	})

    // 点击刷新
    $('#TT').on('click' , function() {
        document.location.reload()
    })
    
    
    // 点击删除
    $('tbody').on('click', '.del', function () {
        const id = $(this).attr('data-id')
        // console.log(id);
        axios.get(`/ydd_article/del` , {
            params :{
                id
            }
        }).then(({ errmsg, errno }) => {
            // console.log(res);
            if (errno) return layer.msg(errmsg, { icon: 5, time: 1000 })
            layer.confirm('确认删除吗?', index => {
                getList()
                layer.close(index)
            });
        })

    })

    // 分类下拉框
    axios.get('/ydd_cate/all').then(({ data: { data } }) => {
        console.log(data);
        $('[name="cateid"]').append(data.map(({ catename, id }) => catename ? `
           <option value="${id}" >${catename}</option>` : '').join(''))
        form.render()
    })

    // 重置
    $('#reset').on('click', () => {
		const obj = {
			start_time: '',
			end_time: "",
			title: '',
			cateid: '',
			page: 1,
			limit: 10,
		}
		Object.assign(key, obj)
		getList()
		$('.head')[0].reset()
	})

	// 点击切换小框架
    $('#filter').on('click' , () => {
        $('.TT').toggle()
    })

    // 封装分页器
    const laypage = layui.laypage
    function renderPage(total) {
        laypage.render({
            elem: 'page', //注意，这里的 test1 是 ID，不用加 # 号
            count: total,//数据总数，从服务端得到
            limit: key.limit,
            curr: key.page,
            limits: [10, 20, 40, 50, 100], // 如果 layout 参数开启了 limit，则会出现每页条数的select选择框
            layout: ['limit', 'prev', 'page', 'next', 'skip'],//自定义排版,页面显示元素
            // 分页器的每项值改动都会调用这个回调函数
            jump: (obj, first) => { // obj 为每次分页器改变后的新值,
                // first来控制是过滤只要分页器直接改变时才执行的代码
                key.page = obj.curr
                key.limit = obj.limit
                //首次不执行
                if (!first) getList()
            }
        });
    }

    function getFilterList() {
		const data = []
		$('.flt').each(function () {
			const key = $(this).html()
			const value = $(this).data('id')
			data.push({
				key: key,
				value: value
			})
		})
		return data
	}


	$('.TT').html(getFilterList().map(({ key, value }) => `
	<dt data-id=${value}>
      <i class="layui-icon layui-icon-component"></i>
      <label >
        <input type="checkbox" class="checkall" checked>
        <span class="active">${key}</span>
      </label>
  </dt>`).join(''))



	function getFilter() {
		$('.TT span').each(function () {
			$(this)[0].className = $(this).siblings('input').prop('checked') ? 'active' : ''
		})
	}


	$('.TT').on('click', 'dt', function () {
		getFilter() 
		const key = $(this).data('id')
		// console.log($(this).data('id'))
		filter[key] = $(this).find('input').prop('checked')
        console.log(filter[key]); 
		$('thead').html(`
		<tr>
      ${filter.isID ? `<th>ID</th>` : ''}
      ${filter.isTitle ? `<th class="flt" data-id="isTitle">标题</th>` : ''}
      ${filter.iscatename ? `<th class="flt" data-id="iscatename">分类名</th>` : ''}
      ${filter.isPic ? `<th class="flt" data-id="isPic">图片</th>` : ''}
      ${filter.isCreate_date ? `<th class="flt" data-id="isCreate_date">创建时间</th>` : ''}
      ${filter.isIshot ? `<th class="flt" data-id="isIshot">是否推荐</th>` : ''}
      ${filter.isIstop ? `<th class="flt" data-id="isIstop">是否置顶</th>` : ''}
      ${filter.isStatus ? `<th class="flt" data-id="isStatus">文章状态</th>` : ''}
      <th>操作</th>
    </tr>`)
		$('colgroup').html(`
		<tr>
      ${filter.isID ? `<col width="50">` : ''}
      ${filter.isTitle ? `<col width="200">` : ''}
      ${filter.iscatename ? `<col width="50">` : ''}
      ${filter.isPic ? `<col width="300">` : ''}
      ${filter.isCreate_date ? `<col width="200">` : ''}
      ${filter.isIshot ? `<col width="100">` : ''}
      ${filter.isIstop ? `<col width="100">` : ''}
      ${filter.isStatus ? `<col width="100">` : ''}
			<col class="sum" width="auto">
    </tr>`)

		getList()
	})
    
    // 点击新增跳转
    $('.list .add').on('click', () => location.href = '/youdianda_static/article-add.html')
})

 